package com.yh.autobio.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.jjobes.slidedatetimepicker.SlideDateTimeListener;
import com.github.jjobes.slidedatetimepicker.SlideDateTimePicker;
import com.google.gson.Gson;
import com.yh.autobio.AppConfig;
import com.yh.autobio.AppContext;
import com.yh.autobio.R;
import com.yh.autobio.api.ErrorHandler;
import com.yh.autobio.api.RetrofitSingleton;
import com.yh.autobio.base.BaseFragment;
import com.yh.autobio.common.FullyLinearLayoutManager;
import com.yh.autobio.common.PLog;
import com.yh.autobio.common.StringUtils;
import com.yh.autobio.common.TDevice;
import com.yh.autobio.common.Time;
import com.yh.autobio.common.UIHelper;
import com.yh.autobio.component.dialog.DialogHelp;
import com.yh.autobio.gddb.gbmanager.BackMatManager;
import com.yh.autobio.gddb.gbmanager.MatHeadManager;
import com.yh.autobio.gddb.gbmanager.MatManager;
import com.yh.autobio.gddb.gdbean.BackMatBean;
import com.yh.autobio.gddb.gdbean.MatBean;
import com.yh.autobio.gddb.gdbean.MatHeadBean;
import com.yh.autobio.modules.adatper.BackMatAdapter;
import com.yh.autobio.modules.bean.CM;
import com.yh.autobio.modules.bean.CustPhone;
import com.yh.autobio.modules.bean.MatSubBean;
import com.yh.autobio.modules.bean.Result;
import com.yh.autobio.modules.bean.SimpleBackPage;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.yh.autobio.AppConfig.SCN_CUST_ACTION_SCODE;
import static com.yh.autobio.R.id.tv_date;

/**
 * =========================
 * 版权所有，违法必究
 * 作者：john
 * <p>
 * 工程：FoodBarcode
 * <p>
 * 文件名：BackMatFragment
 * <p>
 * 创建时间：2017.05.27.14:33
 * *****************************
 */
public class BackMatFragment extends BaseFragment implements BackMatAdapter.OnSaleAddAdapterListern {
    @InjectView(tv_date)
    TextView tvDate;
    @InjectView(R.id.ll_date)
    LinearLayout llDate;
    @InjectView(R.id.tv_gh_unit)
    TextView tvGhUnit;
    @InjectView(R.id.ll_gh_unit)
    LinearLayout llGhUnit;
    @InjectView(R.id.tv_sales_way)
    TextView tvSalesWay;
    @InjectView(R.id.ll_sales_way)
    LinearLayout llSalesWay;
    @InjectView(R.id.tv_bz)
    EditText tvSsMoney;
    @InjectView(R.id.tv_pgno)
    TextView tvPgno;
    @InjectView(R.id.tv_pgno_type)
    TextView tvPgnoType;
    @InjectView(R.id.ll_pgno_type)
    LinearLayout llPgnoType;
    @InjectView(R.id.ll_pgno)
    LinearLayout llPgno;


    @InjectView(R.id.tv_sale)
    TextView tvSale;
    @InjectView(R.id.ll_sale)
    LinearLayout llSale;
    @InjectView(R.id.tv_cust_phone)
    TextView tvCustPhone;
    @InjectView(R.id.ll_cust_phone)
    LinearLayout llCustPhone;
    @InjectView(R.id.tv_fh_warehouse)
    TextView tvFhWarehouse;
    @InjectView(R.id.ll_fh_warehouse)
    LinearLayout llFhWarehouse;
    @InjectView(R.id.recyclerview)
    RecyclerView mRecycleview;

    private BackMatAdapter mAdapter;
    ArrayList<BackMatBean> checkedCKS;

    private BroadcastReceiver mSamDataReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(SCN_CUST_ACTION_SCODE)) {
                String message = intent.getStringExtra(AppConfig.SCN_CUST_EX_SCODE);
                handleOtherText(message);
            }
        }
    };

    //扫描条码只对应一个物料时的添加流程
    private void onlyMatInsert(String barcode) {
        //先判断已添加的中是否存在
        List<BackMatBean> listMatBean = mAdapter.getBackList();
        for (int i = 0; i < listMatBean.size(); i++) {
            BackMatBean matBean = listMatBean.get(i);
            String id = matBean.getBarcode();
            if (barcode.equals(id)) {
                int count = Integer.parseInt(matBean.getCount()) + 1;
                matBean.setCount(count + "");
                BackMatManager.getInstance(mActivity).updateItemCount(matBean);
                mRecycleview.setAdapter(mAdapter);
                return;
            }
        }

        MatBean matById = MatManager.getInstance(mActivity).getMatById(barcode, "0");
        BackMatBean backMatBean = new BackMatBean();

        backMatBean.setBarcode(matById.getBarcode());
        backMatBean.setUnitgroup_id(matById.getUnitgroup_id());
        backMatBean.setCredit(matById.getCredit());
        backMatBean.setDefunitId(matById.getDefunitId());
        backMatBean.setFtype(matById.getFtype());
        backMatBean.setId(matById.getId());
        backMatBean.setModel(matById.getModel());
        backMatBean.setName(matById.getName());
        backMatBean.setNumber(matById.getNumber());
        backMatBean.setSaleprice(Double.parseDouble(matById.getSaleprice()));
        backMatBean.setUnit_id(matById.getUnit_id());
        backMatBean.setUnitgroup_name(matById.getUnitgroup_name());
        backMatBean.setUnit_name(matById.getUnit_name());
        backMatBean.setCount("1");
        backMatBean.setBaseName(matById.getBaseName());
        backMatBean.setBaseunit(matById.getBaseunit());
        backMatBean.setReprice(matById.getReprice());
        backMatBean.setUnitType("0");//0代表baseName 1代表unit_name
        backMatBean.setUserName(AppContext.getInstance().getCurrentUser().getName());
        BackMatManager.getInstance(mActivity).insertBackMat(backMatBean);//缓存
        checkedCKS.add(backMatBean);
        mAdapter = new BackMatAdapter(mActivity, checkedCKS, BackMatFragment.this);
        mRecycleview.setAdapter(mAdapter);


    }

    //从多个物料中选择一个加入缓存并刷新页面
    private void choiceSingleMat(String barcode) {
        //拿到该条码对应多个物料
        final ArrayList<MatBean> mulMat = MatManager.getInstance(mActivity).getMulMat(barcode, "0");
        String[] strings = new String[mulMat.size()];
        for (int i = 0; i < mulMat.size(); i++) {
            strings[i] = mulMat.get(i).getName();
        }
        DialogHelp.getSingleChoiceDialog(mActivity, "种类", strings, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String id = mulMat.get(i).getId();
                //先判断已添加的中是否存在
                ArrayList<BackMatBean> listMatBean = mAdapter.getBackList();
                for (int j = 0; j < listMatBean.size(); j++) {
                    BackMatBean matBeanCount = listMatBean.get(j);
                    String ids = matBeanCount.getId();
                    if (id.equals(ids)) {//已添加过同类型物料
                        int count = Integer.parseInt(listMatBean.get(j).getCount()) + 1;
                        matBeanCount.setCount(count + "");
                        BackMatManager.getInstance(mActivity).updateItemCount(matBeanCount);
                        mRecycleview.setAdapter(mAdapter);
                        dialogInterface.dismiss();
                        return;
                    }
                }

                MatBean matById = MatManager.getInstance(mActivity).getMatById(id);
                BackMatBean backMatBean = new BackMatBean();

                backMatBean.setBarcode(matById.getBarcode());
                backMatBean.setUnitgroup_id(matById.getUnitgroup_id());
                backMatBean.setCredit(matById.getCredit());
                backMatBean.setDefunitId(matById.getDefunitId());
                backMatBean.setFtype(matById.getFtype());
                backMatBean.setId(matById.getId());
                backMatBean.setModel(matById.getModel());
                backMatBean.setName(matById.getName());
                backMatBean.setNumber(matById.getNumber());
                backMatBean.setSaleprice(Double.parseDouble(matById.getSaleprice()));
                backMatBean.setUnit_id(matById.getUnit_id());
                backMatBean.setUnitgroup_name(matById.getUnitgroup_name());
                backMatBean.setUnit_name(matById.getUnit_name());
                backMatBean.setCount("1");
                backMatBean.setBaseName(matById.getBaseName());
                backMatBean.setBaseunit(matById.getBaseunit());
                backMatBean.setReprice(matById.getReprice());
                backMatBean.setUnitType("0");//0代表baseName 1代表unit_name
                backMatBean.setUserName(AppContext.getInstance().getCurrentUser().getName());

                BackMatManager.getInstance(mActivity).insertBackMat(backMatBean);//缓存
                checkedCKS.add(backMatBean);
                mAdapter = new BackMatAdapter(mActivity, checkedCKS, BackMatFragment.this);
                mRecycleview.setAdapter(mAdapter);

                dialogInterface.dismiss();
            }
        }).show();
    }


    private void handleOtherText(String text) {

        //先去判断扫描的单号是否存在
        boolean matExist = MatManager.getInstance(mActivity).isMatExist(text, "0");
        if (matExist) {//存在
            //再去判断扫描的单号对应几个物料
            boolean mulMat1 = MatManager.getInstance(mActivity).isMulMat(text, "0");
            if (mulMat1) {//为true说明对应多个物料
                choiceSingleMat(text);
            } else {//走else说明只对应一个物料
                onlyMatInsert(text);
            }
        } else {//不存在
            Snackbar.make(mActivity.getWindow().getDecorView(), "出库单不匹配，请重新扫描或同步数据！", Snackbar.LENGTH_SHORT).show();
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = View.inflate(mActivity, R.layout.fragment_back_mat, null);
        ButterKnife.inject(this, view);
        initView(view);
        initData();
        return view;
    }

    @Override
    public void initView(View view) {
        super.initView(view);
        setHasOptionsMenu(true);
        String time = MatHeadManager.getInstance(mActivity).getHeadValue("时间", "3");
        String ghdw = MatHeadManager.getInstance(mActivity).getHeadValue("购货单位", "3");
        String xsfs = MatHeadManager.getInstance(mActivity).getHeadValue("销售方式", "3");
        String hyb = MatHeadManager.getInstance(mActivity).getHeadValue("货运部", "3");
        String sklx = MatHeadManager.getInstance(mActivity).getHeadValue("收款类型", "3");
        String ywy = MatHeadManager.getInstance(mActivity).getHeadValue("业务员", "3");
        String kfdh = MatHeadManager.getInstance(mActivity).getHeadValue("客服电话", "3");
        String fhck = MatHeadManager.getInstance(mActivity).getHeadValue("发货仓库", "3");

        if (!StringUtils.isEmpty(time)) {
            tvDate.setText(time);
        } else {
            tvDate.setText(Time.getNowYMDHMSTime());
        }
        tvSalesWay.setText(xsfs);
        tvGhUnit.setText(ghdw);
        tvPgno.setText(hyb);
        tvSale.setText(ywy);
        tvCustPhone.setText(kfdh);
        tvFhWarehouse.setText(fhck);
        tvPgnoType.setText(sklx);


        llGhUnit.setOnClickListener(this);
        llSalesWay.setOnClickListener(this);
        llFhWarehouse.setOnClickListener(this);
        llCustPhone.setOnClickListener(this);
        llSale.setOnClickListener(this);
        llDate.setOnClickListener(this);
        llPgno.setOnClickListener(this);
        llPgnoType.setOnClickListener(this);

        FullyLinearLayoutManager linearLayoutManager = new FullyLinearLayoutManager(getContext());
        mRecycleview.setNestedScrollingEnabled(false);
        //设置布局管理器
        mRecycleview.setLayoutManager(linearLayoutManager);

    }

    @Override
    public void initData() {
        super.initData();
        TDevice.hideSoftKeyboard(mActivity);

        IntentFilter intentFilter = new IntentFilter(SCN_CUST_ACTION_SCODE);
        mActivity.registerReceiver(mSamDataReceiver, intentFilter);

        checkedCKS = new ArrayList<>();
        ArrayList<BackMatBean> allMats = BackMatManager.getInstance(mActivity).getAllBack();
        checkedCKS.addAll(allMats);
        mAdapter = new BackMatAdapter(mActivity, checkedCKS, this);
        mRecycleview.setAdapter(mAdapter);


    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.send_menu, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.send_btn:
                subMat();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    public void subMat() {
//        String etPaper = tvPaper.getText().toString(); //摘要
        String etMoney = tvSsMoney.getText().toString();   //实收金额
//        String etFixPhone = tvFixPhone.getText().toString(); //固定电话
//        String etMobPhone = tvMobPhone.getText().toString();   //移动电话
        String tvDates = tvDate.getText().toString();   //时间
        String tvGhUnits = tvGhUnit.getText().toString();  //购货单位
        String tvSalesWays = tvSalesWay.getText().toString();//销售方式
        String tvPgnos = tvPgno.getText().toString(); //货运部
        String tvPgnoTypes = tvPgnoType.getText().toString(); //收款类型
        String tvSales = tvSale.getText().toString();  //业务员
        String tvCustPhones = tvCustPhone.getText().toString();  //客服电话
        String tvFhWarehouses = tvFhWarehouse.getText().toString();  //发货仓库

        if (!StringUtils.isEmpty(tvGhUnits) && !StringUtils.isEmpty(tvSalesWays) && !StringUtils.isEmpty(tvPgnoTypes) &&
                !StringUtils.isEmpty(tvSales) && !StringUtils.isEmpty(tvCustPhones) && !StringUtils.isEmpty(tvFhWarehouses)) {

            if (!StringUtils.isToday(tvDates)){
                Snackbar.make(mActivity.getWindow().getDecorView(), "请修改提交日期！", Snackbar.LENGTH_SHORT).show();
                return;
            }

            MatSubBean.TableHead head = new MatSubBean.TableHead();
            String fhckId = MatHeadManager.getInstance(mActivity).getIDByName("发货仓库", "3");
            String ywyId = MatHeadManager.getInstance(mActivity).getIDByName("业务员", "3");
            String ghdwId = MatHeadManager.getInstance(mActivity).getIDByName("购货单位", "3");
            String xsfsId = MatHeadManager.getInstance(mActivity).getIDByName("销售方式", "3");
            String sklxId = MatHeadManager.getInstance(mActivity).getIDByName("收款类型", "3");
            String kfdhId = MatHeadManager.getInstance(mActivity).getIDByName("客服电话", "3");
            String hybId = MatHeadManager.getInstance(mActivity).getIDByName("货运部", "3");

            head.setFDate(tvDates);
            head.setFCusPhone(kfdhId);
            head.setFDCStockID(fhckId);
//            head.setFExplanation(etPaper);
            head.setFEmpID(ywyId);
            head.setFRealReceive(etMoney);
            head.setFSaleStyle(xsfsId);
            head.setFStockDept(hybId);
            head.setFSupplyID(ghdwId);
            head.setFReceiveType(sklxId);
            head.setFtype("-1");

            ArrayList<BackMatBean> allMats = BackMatManager.getInstance(mActivity).getAllBack();

            if (allMats == null || allMats.size() == 0) {
                Snackbar.make(mActivity.getWindow().getDecorView(), "请扫描物料，再提交", Snackbar.LENGTH_SHORT).show();
                return;
            }
            List<MatSubBean.TableBody> bodys = new ArrayList<>();
            for (int i = 0; i < allMats.size(); i++) {
                BackMatBean count1 = allMats.get(i);
                MatSubBean.TableBody body = new MatSubBean.TableBody();
                String count = count1.getCount();
                double saleprice = count1.getSaleprice();
                double Amount = Integer.parseInt(count) * saleprice;

                if ("0".equals(count1.getUnitType())) {//0代表baseName 1代表unit_name
                    body.setFUnitId(count1.getBaseunit());
                } else if ("1".equals(count1.getUnitType())) {
                    body.setFUnitId(count1.getUnit_id());
                }

                body.setFProductID(count1.getId());
                body.setFSaleAmount("" + -Amount);
                body.setFSalePrice(count1.getSaleprice() + "");
                body.setFQty(-Integer.parseInt(count1.getCount()) + "");

                String value = MatHeadManager.getInstance(mActivity).getIDByName("发货仓库", "3");

                String tdcStockID = count1.getTDCStockID();
//                String cusvalue = count1.getFDCStockID();
                if (!StringUtils.isEmpty(tdcStockID)) {
                    body.setFStockId(tdcStockID);
                } else if (!StringUtils.isEmpty(value)) {
                    body.setFStockId(value);
                } else {
                    body.setFStockId("0");
                }
                bodys.add(body);
            }

            showWaitDialog();
            MatSubBean matSubBean = new MatSubBean();
            matSubBean.setBodyList(bodys);
            matSubBean.setHeadDetaili(head);
            Gson gson = new Gson();
            String json = gson.toJson(matSubBean);
            PLog.i("lj", json);
            String token = AppContext.getInstance().getProperty(AppConfig.PRIVATE_TOKEN);
            CM cm = new CM();
            cm.setToken(token);
            cm.setData(json);
            RetrofitSingleton.getApiService(mActivity).
                    StockBillSubmit(cm)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(observer);
        } else {
            Snackbar.make(mActivity.getWindow().getDecorView(), "必填信息不能为空！", Snackbar.LENGTH_SHORT).show();
        }


    }

    private BackMatBean position;

    @Override
    public void onFHCKClick(BackMatBean position) {
        this.position = position;
        Bundle bundle = new Bundle();
        bundle.putString("type", "fhck");
        UIHelper.showSimpleBackForResult(this, mActivity, 7, SimpleBackPage.CUST_PHEON, bundle, "发货仓库");
    }

    //点击单位回调
    @Override
    public void onDwClick(final BackMatBean Bean, final TextView tvUnit) {
        final String[] strings = {Bean.getBaseName(), Bean.getUnit_name()};
        DialogHelp.getSingleChoiceDialog(mActivity, "单位", strings, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
//                Snackbar.make(mActivity.getWindow().getDecorView(),"点击了："+strings[i],Snackbar.LENGTH_SHORT).show();
//                tvUnit.setText(strings[i]);
                Bean.setUnitType(i + "");
                dialogInterface.dismiss();
                mAdapter.notifyDataSetChanged();
            }
        }).show();
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        Bundle bundle = new Bundle();
        switch (v.getId()) {
            case R.id.ll_pgno:
                bundle.putString("type", "hyb");
                UIHelper.showSimpleBackForResult(this, mActivity, 6, SimpleBackPage.CUST_PHEON, bundle, "货运部");
                break;
            case R.id.ll_gh_unit:
                bundle.putString("type", "ghdw");
                UIHelper.showSimpleBackForResult(this, mActivity, 1, SimpleBackPage.CUST_PHEON, bundle, "购货单位");
                break;
            case R.id.ll_sales_way:
                bundle.putString("type", "xsfs");
                UIHelper.showSimpleBackForResult(this, mActivity, 2, SimpleBackPage.CUST_PHEON, bundle, "销售方式");
                break;
            case R.id.ll_pgno_type:
                bundle.putString("type", "sklx");
                UIHelper.showSimpleBackForResult(this, mActivity, 3, SimpleBackPage.CUST_PHEON, bundle, "收款类型");
                break;
            case R.id.ll_cust_phone:
                bundle.putString("type", "khdh");
                UIHelper.showSimpleBackForResult(this, mActivity, 0, SimpleBackPage.CUST_PHEON, bundle, "客服电话");
                break;
            case R.id.ll_sale:
                bundle.putString("type", "ywy");
                UIHelper.showSimpleBackForResult(this, mActivity, 4, SimpleBackPage.CUST_PHEON, bundle, "业务员");
                break;
            case R.id.ll_fh_warehouse:
                bundle.putString("type", "fhck");
                UIHelper.showSimpleBackForResult(this, mActivity, 5, SimpleBackPage.CUST_PHEON, bundle, "发货仓库");
                break;
            case R.id.ll_date:
                new SlideDateTimePicker.Builder(getFragmentManager())
                        .setListener(listener)
                        .setInitialDate(new Date())
                        .build()
                        .show();
                break;
        }
    }

    private SlideDateTimeListener listener = new SlideDateTimeListener() {

        @Override
        public void onDateTimeSet(Date date) {
            String str = StringUtils.getDateString(date);
            tvDate.setText(str);
            MatHeadBean HeadBean = new MatHeadBean();
            HeadBean.setId("时间");
            HeadBean.setValue(str);
            HeadBean.setName("时间");
            HeadBean.setFtype("3");

            MatHeadManager.getInstance(mActivity).insertOrReplace(HeadBean);
        }

        @Override
        public void onDateTimeCancel() {
        }
    };

    private String id;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            final CustPhone item = (CustPhone) data.getSerializableExtra("item");
            if (item != null) {
                MatHeadBean HeadBean = new MatHeadBean();
                HeadBean.setId(item.getId());
                HeadBean.setValue(item.getName());
                HeadBean.setFtype("3");//2代表销售出库，3代表退货
                switch (requestCode) {
                    case 0:
                        tvCustPhone.setText(item.getName());
                        HeadBean.setName("客服电话");
                        MatHeadManager.getInstance(mActivity).insertOrReplace(HeadBean);
                        break;
                    case 1:
                        tvGhUnit.setText(item.getName());
                        HeadBean.setName("购货单位");
                        MatHeadManager.getInstance(mActivity).insertOrReplace(HeadBean);
                        break;
                    case 2:
                        tvSalesWay.setText(item.getName());
                        HeadBean.setName("销售方式");
                        MatHeadManager.getInstance(mActivity).insertOrReplace(HeadBean);
                        break;
                    case 3:
                        tvPgnoType.setText(item.getName());
                        HeadBean.setName("收款类型");
                        MatHeadManager.getInstance(mActivity).insertOrReplace(HeadBean);
                        break;
                    case 4:
                        tvSale.setText(item.getName());
                        HeadBean.setName("业务员");
                        MatHeadManager.getInstance(mActivity).insertOrReplace(HeadBean);
                        break;
                    case 5:
                        tvFhWarehouse.setText(item.getName());
                        HeadBean.setName("发货仓库");
                        MatHeadManager.getInstance(mActivity).insertOrReplace(HeadBean);

//                        mRecycleview.setAdapter(mAdapter);
                        mAdapter.notifyDataSetChanged();
                        //更新表体
                        Intent intent = new Intent(AppConfig.UPDATA_BODY);
                        mActivity.sendBroadcast(intent);
                        break;
                    case 6:
                        tvPgno.setText(item.getName());
                        HeadBean.setName("货运部");
                        MatHeadManager.getInstance(mActivity).insertOrReplace(HeadBean);
                        break;
                    case 7://adapter中点击发货仓库 自选的仓库
//                        HeadBean.setName("CUS发货仓库");
//                        MatHeadManager.getInstance(mActivity).insertOrReplace(HeadBean);
//                        mAdapter.notifyItemChanged(position);

                        if (position != null) {
                            position.setTDCStockID(item.getId());
                            position.setTDCStockName(item.getName());
//                            BackMatManager.getInstance(mActivity).updateTDCStock(position);
                            mAdapter.notifyDataSetChanged();
                        }

                        break;
                }
            }
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        try {
            mActivity.unregisterReceiver(mSamDataReceiver);
        } catch (Exception ex) {
        }
        ButterKnife.reset(this);
    }

    Observer<Result> observer = new Observer<Result>() {
        @Override
        public void onCompleted() {
            PLog.d("s", "onCompleted");
            hideWaitDialog();
        }

        @Override
        public void onError(Throwable e) {
            PLog.d("s", e.getMessage());
            String errBody = ErrorHandler.handle(e);
            Snackbar.make(getActivity().getWindow().getDecorView(), errBody, Snackbar.LENGTH_SHORT).show();
            hideWaitDialog();
        }

        @Override
        public void onNext(Result result) {
            hideWaitDialog();
            if (result.isSuccess()) {
                MatHeadManager.getInstance(mActivity).delAllMatHead();
                BackMatManager.getInstance(mActivity).delAllMat();//提交成功后删除缓存
                mActivity.finish();
            } else {
                Snackbar.make(mActivity.getWindow().getDecorView(), result.getMessage(), Snackbar.LENGTH_SHORT).show();
            }
        }
    };

}
